//
//  BlueToothViewController.m
//  GetFit3.0
//
//  Created by 秀才 on 2016/12/12.
//  Copyright © 2016年 lxc. All rights reserved.
//

#import "BlueToothViewController.h"
#import "FileModelEntity.h"

@interface BlueToothViewController ()<UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate>{
    NSMutableArray *_dataArr;
    UITableView    *_tableView;
    UIButton       *leftButton;
}
@end

@implementation BlueToothViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (self.navigationController.navigationBar.hidden == YES) {
        self.view.backgroundColor = BBIGLIGHTCOLOR;
    }
    if (!KK_BLEConnect.centerPowerOn && _type == 1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:SN_Text(@"检测到你的手机蓝牙功能未启用，请前往手机的[设置]启用蓝牙功能")
                                                        message:@" " delegate:self
                                              cancelButtonTitle:nil
                                              otherButtonTitles:SN_Text(@"确定"),SN_Text(@"取消"), nil];
        [[UIView appearance] setTintColor:UIColorRGB(72, 72, 72)];
        [alert show];
    }
    
    if(KK_BLEConnect.centerPowerOn)
    {
        [self searchBlueTooth];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)addNavBarViews {
    UIView *StateView = [[UIView alloc] init];
    
    StateView.frame           = CGRectMake(0, 0, kSCREEN_WIDTH, 20);
    StateView.backgroundColor = BBIGSTATECOLOR;
    [self.view addSubview:StateView];
    
    UIView *naView = [[UIView alloc] init];
    naView.frame           = CGRectMake(0, 20+FitSimpleIpx(0, 20), kSCREEN_WIDTH, 44);
    naView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:naView];
    
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 20+FitSimpleIpx(0, 20), screenWidth, 44)];
    lable.textColor     = [UIColor blackColor];
    lable.font          = SNFONT(17);
    lable.textAlignment = NSTextAlignmentCenter;
    lable.text          = HHH_Text(@"扫描手环");
    
    [self.view addSubview:lable];
    
    leftButton       = [[UIButton alloc] init];
    leftButton.frame = CGRectMake(5, 20+FitSimpleIpx(0, 20), 44, 44);
    [leftButton setImageNormal:@"进入"];
    [leftButton addTarget:self action:@selector(leftbuttonClick) forControlEvents:UIControlEventTouchUpInside];
    leftButton.hidden = _type == 0 ? YES : NO;
    [self.view addSubview:leftButton];
    
    UIButton *skipButton       = [[UIButton alloc] init];
    skipButton.frame = CGRectMake(HHHWIDTH -70, 20+FitSimpleIpx(0, 20), 60, 44);
    [skipButton addTarget:self action:@selector(functionSetRight) forControlEvents:UIControlEventTouchUpInside];
    skipButton.hidden = _type == 1 ? YES : NO;
    [skipButton setTitleColor:SNCOLORBLACK forState:UIControlStateNormal];
    [skipButton setTitle:SN_Text(@"跳过") forState:UIControlStateNormal];
    [self.view addSubview:skipButton];
}

- (void)functionSetRight
{
    [kK_App enterMainVc];
    [[XNProgressHUD shared]dismiss];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[XNProgressHUD shared]dismiss];
}

- (void)leftbuttonClick {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BBIGLIGHTCOLOR;
    [self addNavBarViews];
    [SN_Net getDeviceSFromServerWithSuccess:nil fail:nil];
    //table
    _tableView                 = [[UITableView alloc]initWithFrame:CGRectMake(0, 64+FitSimpleIpx(0, 20), screenWidth, screenHeight - FitH(60) - 64-FitSimpleIpx(0, 20)) style:UITableViewStylePlain];
    _tableView.backgroundColor = BBIGLIGHTCOLOR;
    _tableView.delegate        = self;
    _tableView.dataSource      = self;
    _tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    _dataArr = [NSMutableArray array];
    [self setExtraCellLineHidden:_tableView];
    _boindState = NO;
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame  = CGRectMake(0, 0, HHHWIDTH*4/5, FitH(40));
    searchBtn.center = CGPointMake(self.view.centerX, HHHHEIGHT-FitH(40));
    [searchBtn setTitleNormal:SN_Text(@"扫描周边设备")];
    [searchBtn setBackgroundColor:[UIColor blackColor]];
    [searchBtn addTouchUpTarget:self action:@selector(searchBlueTooth)];
    [self.view addSubview:searchBtn];
    
    UIImageView *shadowLine = [[UIImageView alloc] init];
    shadowLine.frame = SNFRAME(0, 20+FitSimpleIpx(0, 20) + 44 -2, HHHWIDTH, 2);
    shadowLine.image = [UIImage image:@"lineImage"];
    [self.view addSubview:shadowLine];
}

- (void)updateModel:(KKBLEModel *)model type:(KKBLEUpdateType)type {
    //    NSLog(@"刷新蓝牙状态:%@ mac >>>>%@ rssi>>%@", model.bleName, model.bleMAC, model.bleRSSI);
    if (type == KKBLEUpdatePowerOff && _type == 0) {
        [[XNProgressHUD shared]dismiss];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:SN_Text(@"检测到你的手机蓝牙功能未启用，请前往手机的[设置]启用蓝牙功能")
                                                        message:@" " delegate:self
                                              cancelButtonTitle:nil
                                              otherButtonTitles:SN_Text(@"确定"), nil];
        [[UIView appearance] setTintColor:UIColorRGB(72, 72, 72)];
        [alert show];
        return;
    }
    
    NSArray *sortArray = [KK_BLEConnect.devicesArray sortedArrayUsingComparator:^NSComparisonResult (id _Nonnull obj1, id _Nonnull obj2) {
        KKBLEModel *model1 = (KKBLEModel *)obj1;
        KKBLEModel *model2 = (KKBLEModel *)obj2;
        return [model1.bleRSSI compare:model2.bleRSSI];
    }];
    _dataArr = [NSMutableArray arrayWithArray:sortArray];
    
    _tableView.hidden = _dataArr.count ? NO : YES;
    if (type == KKBLEUpdateDidConnect) {
        [[XNProgressHUD shared]dismiss];
        _infoLabel.text = HHH_Text(@"绑定成功...");
        SHOWMBProgressHUD(HHH_Text(@"connection complete"), nil, nil, NO, 2.0);
        [[FileModelEntity sharedInstance]checkUpdateFirmwareInfo];
        [kK_App enterMainVc];
    } else if (type == KKBLEUpdateDisConnect) {
        [[XNProgressHUD shared]dismiss];
        if (_dataArr.count == 0) {
            _infoLabel.text = HHH_Text(@" Did not find the bracelet, click the Bluetooth to re-binding  ");
        } else {
            _infoLabel.text = HHH_Text(@"  Bind the device and click to Rebind ");
        }
    }
    [_tableView reloadData];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    //    if ([[UIDevice currentDevice]systemVersion].floatValue >= 10.0) {
    //        // iOS10之后不允许跳转到设置的子页面，只允许跳转到设置界面(首页)，据说跳转到系统设置子页面，但同时会加大遇到审核被拒的可能性
    //        NSURL *url = [NSURL URLWithString:@"App-Prefs:root=Bluetooth"];
    //        if ([[UIApplication sharedApplication] canOpenURL:url]) {
    //            [[UIApplication sharedApplication] openURL:url];
    //        }
    //    } else {
    //        NSURL *url = [NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"];
    //        if ([[UIApplication sharedApplication] canOpenURL:url]) {
    //            [[UIApplication sharedApplication] openURL:url];
    //        }
    //    }
    if (buttonIndex == 0) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}

- (void)setExtraCellLineHidden:(UITableView *)tableView {
    UIView *view = [UIView new];
    
    view.backgroundColor = [UIColor clearColor];
    [_tableView setTableFooterView:view];
}

- (void)setType:(NSInteger)type {
    _type = type;
}

- (void)stopSearchBle {
    if (_dataArr.count == 0) {
        _infoLabel.text = HHH_Text(@"  No device, please click the Bluetooth icon to re-scan ");
    } else {
        _infoLabel.text = HHH_Text(@" The scan is complete,click to Bind your device  ");
    }
}

- (void)searchBlueTooth {
    
    if (!KK_BLEConnect.centerPowerOn) {
        SHOWMBProgressHUD(HHH_Text(@"蓝牙未打开"), nil, nil, NO, 3.0);
        return;
    }
    
    NSMutableArray *arr = [[NSUserDefaults standardUserDefaults] objectForKey:@"DeviceNameArr"];
    
    if (arr.count == 0) {
        [SN_Net getDeviceSFromServerWithSuccess:nil fail:nil];
    }
    [KK_BLEConnect scanWithoutBreakConnect];
    _infoLabel.text = HHH_Text(@"搜索设备中...");
    SHOWMBProgressHUD(HHH_Text(@"搜索设备中..."), nil, nil, NO, 3.0);
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(stopSearchBle) object:nil];
    [self performSelector:@selector(stopSearchBle) withObject:self afterDelay:8.0f];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellID = @"MyBlueToothTableViewCellID";
    UITableViewCell *cell   = [tableView cellForRowAtIndexPath:indexPath];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellID];
        
        cell.contentView.backgroundColor = BBIGLIGHTCOLOR;
        
        UIImageView *rssiImageView = [[UIImageView alloc] init];
        rssiImageView.tag = indexPath.row +100;
        [cell.contentView addSubview:rssiImageView];
        rssiImageView.frame = CGRectMake(HHHWIDTH - 66, 20, 30, 20);
        
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 59, HHHWIDTH, 1)];
        line.backgroundColor = SNCOLORGRAYLINE;
        [cell.contentView addSubview:line];
    }
    
    
    UIImageView *rssiImageView = (UIImageView *)[cell viewWithTag:indexPath.row+100];
    
    KKBLEModel *model = _dataArr[indexPath.row];
    cell.imageView.image      = UIImageNamed(@"手环");
    cell.textLabel.text       = model.bleName;
    cell.detailTextLabel.text = model.bleMAC;
    NSInteger rssi = model.bleRSSI.integerValue;
    //    [rssiImageView setTintColor:[UIColor blackColor]];
    cell.selectedBackgroundView                 = [[UIView alloc] initWithFrame:cell.frame];
    cell.selectedBackgroundView.backgroundColor = SNCOLORGRAYLINE;
    if (rssi < 60) {
        rssiImageView.image = [UIImage image:@"信号1"];
    } else if (rssi < 70) {
        rssiImageView.image = [UIImage image:@"信号2"];
    } else if (rssi < 80) {
        rssiImageView.image = [UIImage image:@"信号3"];
    } else {
        rssiImageView.image = [UIImage image:@"信号4"];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_dataArr.count == 0 || indexPath.row >= _dataArr.count) {
        return ;
    }
    KKBLEModel *model = _dataArr[indexPath.row];
    if (!model.isConnected) {
        NSLog(@"Adv id >>>>%d",model.bleAdvID);
        if (model.bleAdvID == 0) {
            NSString *info = [NSString stringWithFormat:@"%@%@",SN_Text(@"错误!"),SN_Text(@"解除设备绑定")];
            SHOWMBProgressHUD(info, nil, nil, NO, 2.0);
            return;
        }
    }
    
    if (model.isConnected) {
        SHOWMBProgressHUD(HHH_Text(@"success"), nil, nil, NO, 2.0);
    } else {
        _infoLabel.text = HHH_Text(@"  Binding ..");
        if (model) {
            NSString*deviceName = model.bleName;
            if ([[deviceName lowercaseString] isEqualToString:[@"XW_OTA" lowercaseString]] || [[deviceName lowercaseString] isEqualToString:[@"DfuTarg" lowercaseString] ]|| [[deviceName lowercaseString]isEqualToString:[@"B2_OTA" lowercaseString]] ||[[deviceName lowercaseString] isEqualToString:[@"PPlusOTA" lowercaseString]]) {
                SHOWMBProgressHUD(SN_Text(@"发现硬件固件升级"), nil, nil, NO, 2.0);
            }
            else
            {
                [[XNProgressHUD shared]showLoadingWithTitle:@"请等待..." maskType:XNProgressHUDMaskTypeBlack];
                [KK_BLEConnect connectPeripheralWithModel:model];
            }
        }
    }
}

@end

